package com.shiro.authenticator;

import com.shiro.token.CustomLoginToken;
import com.shiro.token.JWTToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**自定义realm认证器
 * @author WxrStart
 * @create 2022-05-22 23:08
 */
@Slf4j
public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {


    /**
     * 重写多realm校验方法，避免无法捕获到realm中的自定义异常
     * 取消执行代码 realm.getAuthenticationInfo(token); 的tey catch
     * 多个realm时候，如果其中一个realm抛出异常则直接抛出异常，类似single方法，
     *
     * @param realms
     * @param token
     * @return
     */
//    @Override
//    protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
//        log.info("CustomModularRealmAuthenticator的doMultiRealmAuthentication调用了");
//        AuthenticationStrategy strategy = getAuthenticationStrategy();
//        AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
//        if (log.isTraceEnabled()) {
//            log.trace("Iterating through {} realms for PAM authentication", realms.size());
//        }
//        for (Realm realm : realms) {
//            aggregate = strategy.beforeAttempt(realm, token, aggregate);
//            if (realm.supports(token)) {
//                log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);
//                AuthenticationInfo info = null;
//                Throwable t = null;
//                info = realm.getAuthenticationInfo(token);
//                //当匹配到info就返回不再继续查询
//                if (info != null) {
//                    return aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);
//                }
//            } else {
//                log.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
//            }
//        }
//        aggregate = strategy.afterAllAttempts(token, aggregate);
//        return aggregate;
//    }


    /**
     *
     * 自定义Authenticator
     * 注意，当需要分别定义处理普通用户和管理员验证的Realm时，对应Realm的全类名应该包含字符串“User”，或者“Admin”。
     * 并且，他们不能相互包含，例如，处理普通用户验证的Realm的全类名中不应该包含字符串"Admin"。
     */
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("CustomModularRealmAuthenticator的doAuthenticate调用了");
        // 判断getRealms()是否返回为空
        assertRealmsConfigured();
        // 所有Realm
        Collection<Realm> realms = getRealms();
        // 强制转换回自定义的CustomizedToken
        if(authenticationToken instanceof CustomLoginToken) {
            CustomLoginToken token1 = (CustomLoginToken) authenticationToken;
            String loginType1 = token1.getLoginType();
            // 登录类型对应的所有Realm
            Collection<Realm> typeRealms = new ArrayList<>();
            for (Realm realm : realms) {
                if (realm.getName().toLowerCase().startsWith(loginType1)){
                    typeRealms.add(realm);
                }
            }

            // 判断是单Realm还是多Realm
            if (typeRealms.size() == 1)
                return doSingleRealmAuthentication(typeRealms.iterator().next(), token1);
            else
                return doMultiRealmAuthentication(typeRealms, token1);
        }else if(authenticationToken instanceof JWTToken) {
            JWTToken token2 = (JWTToken) authenticationToken;
            // 登录类型对应的所有Realm
            Collection<Realm> typeRealms = new ArrayList<>();
            for (Realm realm : realms) {
                if(realm.getName().equals("JwtRealm")){
                    typeRealms.add(realm);
                }
            }

            // 判断是单Realm还是多Realm
            if (typeRealms.size() == 1)
                return doSingleRealmAuthentication(typeRealms.iterator().next(), token2);
            else
                return doMultiRealmAuthentication(typeRealms, token2);
        }else{
            return null;
        }
    }

}